<?php

namespace App\Http\Controllers\Business;

use App\Events\Event;
use App\Events\CourseEvent;
use App\Model\Business\ClasseStuden;
use App\Model\Business\Schedule;
use App\Model\Business\ScheduleStuden;
use App\Model\Foundation\Student;
use App\Model\Foundation\Teacher;
use App\Model\Marketing\Order;
use App\Model\Marketing\Product;
use Illuminate\Http\Request;
use App\Model\Eeoapi\Eeocourse;
use App\Model\System\Token;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;

use App\Model\Business\Classe;
use App\Http\Controllers\MessagePacket;


/**
 * 班课管理
 * Class ClasseController
 * @package App\Http\Controllers\Business
 */
class  ClasseController extends BaseController
{
    use MessagePacket;

    /**
     * 获取单一班级的信息
     * @param $id
     * @return packetMessage
     */
    function getClasse($id)
    {
        $id = intval($id);
        $classe = Classe::find($id);
        if(empty($classe)){
            return $this->fail($classe, '数据不存在');
        }
        return $this->success($classe);
    }


    /**
     * 批量查询班级
     * @param Request $request
     * @return packetMessage
     */
    function getClasses(Request $request)
    {
        $name = '';
        if($request->has('querystr')) {
            $name = $request->get('querystr');
        }
        $limit = 30;
        if($request->has('perPage')){
            $limit = $request->get('perPage');
        }
        $classe = Classe::where('classname', 'like', "%{$name}%")
            ->orwhere('coursename', 'like', "%{$name}%");
        $classes = $classe->paginate($limit)->toarray();

        $data['list'] = $classes['data'];
        unset($classes['data']);
        $data['pager'] = $classes;

        //搜索 已添加学生数，已添加排课数，已完成课时数。
        $temp = [];
        foreach ($data['list'] as $item){
            $schedules = Schedule::where('classeid',$item['classuid'])
                                    ->get()
                                    ->count();
            $finished = Schedule::where('classeid',$item['classuid'])
                                    ->where('endtime','<',date('Y-m-d H:i:s',time()))
                                    ->get()
                                    ->count();
            $studnets = ClasseStuden::where('classeid',$item['classuid'])
                                    ->where('identity',1)->get()->count();
            $item['used_qoutas'] = $studnets;
            $item['added_lessons'] = $schedules;
            $item['finished_lessons'] = $finished;
            $temp[] = $item;
        }
        $data['list'] = $temp;


	if(empty($data['list'])){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }

    /**
     * 获取班级下的所有学生
     * @param Request $request
     * @param $classeid
     * @return  packetMessage
     */
    function getClasseStudent(Request $request, $classeid)
    {
        $sid = $classeid;
        $identity = ClasseStuden::STUENDT;
        if($request->has('classeid')){
            $sid = $request->classeid;
        }
        if($request->has('identity')){
            $identity = $request->get('identity');
        }
        $studentids = ClasseStuden::where('classeid', $sid)->where('identity', $identity)->get();
        if(!$studentids) {
            return $this->fail([], '没有数据');
        }
        $ids = [];
        foreach ($studentids as $k=>$vals){
            $ids[] = $vals['studentuid'];
        }
        $students = Student::find($ids);

        return $this->success($students);
    }


    /**
     * 获取某个学生的班级课程
     * @param Request $request
     * @param $id
     * @return packetMessage
     */
    function getMyClassesForStudent(Request $request, $id)
    {
        $items = ClasseStuden::where('studentuid', $id)->get()->toarray();

        $classeids = [];
        foreach ($items as $item){
            $classeids[] = $item['classeid'];
        }
        $classes = Classe::wherein('classuid', $classeids)->get();
        foreach ($classes as $class){
            $class->master = Teacher::where('teacheruid',$class->master)->value('lastname');
        }
        return $this->success($classes);
    }

    /**
     * 获取某个学生即将开课的课程
     * @param $id
     * @return packetMessage
     */
    function getMyRecentlyClassesForStudent($id){
        $currentTime = date('Y-m-d H:i:s');

        $scheduleids = ScheduleStuden::where('studentuid',$id)
            ->where('identity',1)->pluck('scheduleid');

        $data = [];
        if(!empty($scheduleids)){
            $schedule = Schedule::whereIn('scheduleid',$scheduleids)
                ->where('begintime','>=',$currentTime)->orderBy('begintime')->limit(1)->first();
            if(!empty($schedule)){
                $schedule = $schedule->toArray();
                $class = Classe::where('classuid',$schedule['classeid'])->first();
                if(!empty($class)){
                    $class->master = Teacher::where('teacheruid',$class->master)->value('lastname');
                    $data['class'] = $class;
                    $data['schedule'] = $schedule;
                    return $this->success($data);
                }
            }
        }
        return $this->fail($data, '数据不存在');
    }

    /**
     * 批量更新学生
     * @param Request $request
     * @param $classeid
     * @return array
     * @throws \Exception
     */
    function updateClasseStudents(Request $request, $classeid)
    {
        try{
            # 正式生，旁听生
            $identity = ClasseStuden::STUENDT;
            if($request->has('identity')) {
                $identity = $request->get('identity');
            }
            # 人员列表
            if(!$request->has('students') and !$request->has('length')){
                return $this->fail(false, '缺少学生数据');
            }else{
                if($request->has('students')){
                    $students = $request->get('students');
                }else{
                    $students = [];
                }
            }
	        # 计算班级内学生变更
            $indes = $this->calculateStudents($classeid, $students, $identity);

            # 抛出事件
            $this->dispatchEvent(Event::STUDENT, $classeid, $indes, $identity);

	        # 更新课节下学生列表
            $increms = [];
            $decrems = [];
            $increms = $indes['increms'];
            $decrems = $indes['decrems'];
            $lessons = Schedule::where('classeid', $classeid)->get();
            if(!empty($lessons)){
                $lids = [];
                foreach($lessons as $lesson){
                    $lids[] = $lesson->scheduleid;
                }
                # 批量删除
                if(!empty($decrems)){
                    ScheduleStuden::where('identity', $identity)
                        ->whereIn('scheduleid', $lids)
                        ->whereIn('studentuid', $decrems)
                        ->delete();
                }
                # 批量添加
                if(!empty($increms)){
                    foreach($lids as $lid){
                        foreach($increms as $increm){
                            $fields = ['scheduleid'=>$lid, 'studentuid'=>$increm, 'identity'=>$identity];
                            ScheduleStuden::firstOrCreate($fields);
                        }
                    }
                }
                foreach($lessons as $lesson){
                    $lesson->usequotas = count(ScheduleStuden::getStudentByScheduleID($lesson->scheduleid));
                    if($lesson->usequotas>=1){
                        $lesson->valide();
                    }else{
                        $lesson->unvalide();
                    }
                    $lesson->save();
                }
            }
            # 清除班级学生表下所有该班学生
            ClasseStuden::where('classeid', $classeid)->where('identity', $identity)->delete();

            # 添加现有学生到该班级学生表
            foreach ($students as $student){
                $studentid = $student;
                $csobj = new ClasseStuden();
                $csobj->classeid = $classeid;
                $csobj->identity = $identity;
                $csobj->studentuid = $studentid;
                $csobj->save();
            }
            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 添加一个班级
     * @param Request $request
     * @return packetMessage
     */
    function  addClasse(Request $request)
    {
        try {
            $fields = $request->all();
            $classe = new Classe($fields);
            $classe->created_by = Token::user()->userid;
            $classe->updated_by = Token::user()->userid;
            $classe->save();
            $this->dispatchEvent(Event::CREATE, $classe);
            return $this->success($classe);
        }catch (\Exception $e){
            if($classe instanceof Classe){
                $classe->delete();
            }
            return $this->fail(false, '保存失败: '.$e->getMessage());
        }
    }
    
    /**
     * 更新某个班级的信息
     * @param Request $request
     * @return packetMessage
     */
    function  updateClasse(Request $request, $id)
    {
        try{
            $classe = Classe::find($id);
            $classe->update($request->all());
            $classe->updated_by = Token::user()->userid;
            $classe->save();

            $schedules = Schedule::where('classeid', $id)->where('type', Schedule::LESSON)->get();
            foreach ($schedules as $schedule)
            {
                $schedule->quotas  = $classe->quotas;
                $schedule->coursetypeid = $classe->coursetypeid;
                $schedule->coursetypename  = $classe->coursetypename;
                $schedule->save();
            }

            $this->dispatchEvent(Event::UPDATE, $classe);
            return $this->success($classe);
        }catch (\Exception $e){
            return $this->fail(false,'保存失败:'.$e->getMessage());
        }
    }


    /**
     * 删除某个时间
     * @param $id
     * @return packetMessage
     */
    function  deleteClasse($id)
    {
        try{
            $classe = Classe::find($id);

	        # 删除事件
            $this->dispatchEvent(Event::DELETE, $classe);
            # 删除关联
            $lessons = Schedule::where('classeid', $id)->where('type', Schedule::LESSON)->get();
            foreach($lessons as $lesson){
                $lesson->delete();
                $lid = $lesson->scheduleid;
                ScheduleStuden::where('scheduleid', $lid)->delete();
            }
            Classe::destroy($id);



            return $this->success(true);
        }catch(\Exception $e){
            return $this->fail(false,'删除失败'.$e->getMessage());
        }
    }


    /**
     * 计算班级下的学生变更
     * @param $classeid
     * @param $students
     * @return bool
     */
    protected function calculateStudents($classeid, $students, $identity)
    {
        $olds = [];
        $increms = [];
        $decrems = [];
        $oldStudents = ClasseStuden::where('classeid', $classeid)->where('identity', $identity)->get();
        foreach($oldStudents as $obj){
            $olds[] = $obj->studentuid;
            # 老的不在新的，移除
            if(!in_array($obj->studentuid, $students)){
                $decrems[] = $obj->studentuid;
            }
        }
        foreach($students as $id){
            # 新的不在老的，添加
            if(!in_array($id, $olds)){
                $increms[] = $id;
            }
        }

        # 返回待用
        return ['increms'=>$increms, 'decrems'=>$decrems];
    }


    /**
     * 获取班级下的所有课节
     * @param Request $request
     * @param $id
     * @return array
     */
    public function getMyLessonsInClass(Request $request, $id)
    {
        try{
            $studentuid = $request->get('studentuid');
            $classe = Classe::findOrFail($id);

            $schids = DB::table('schedules')->where('classeid', $id)->where('type', Schedule::LESSON)->pluck('scheduleid')->toarray();

            $scheduleids = DB::table('schedules_students')->wherein('scheduleid', $schids)
                                         ->where('studentuid', $studentuid)
                                         ->pluck('scheduleid')->toarray();

            $schdules = Schedule::wherein('scheduleid', $scheduleids)->get();
            return $this->success($schdules);
        }catch (\Exception $e){
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 触发事件
     * @param $action
     * @param $classe
     * @return string
     * @throws \Exception
     */
    protected function dispatchEvent($action, $classe, $indes=null, $identity=1)
    {
        try{
            if($action <> Event::STUDENT){
                $eventCourse = new CourseEvent($classe, $action);
            }else{
                $classe = Classe::find($classe);
                $eventCourse = new CourseEvent($classe, $action);
                $olds = Student::wherein('studentuid', $indes['decrems'])->get();
                $news = Student::whereIn('studentuid', $indes['increms'])->get();
                $eventCourse->setIdentity($identity);
                $eventCourse->setStudents($news);
                $eventCourse->setStudents($olds, true);
            }
            event($eventCourse);
        }catch (\Exception $e){
            throw $e;
            return $e->getMessage();
        }
    }

}
